/*
 *    Thing Game Library
 *   Copyright (C)2005 - 2010 Eduardo Nunes Pereira (eduardonunesp at gmail dot com)
 *
 *   This program/library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 *   This program/library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 *    You should have received a copy of the GNU Lesser General Public
 * License along with this program/library ; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "Game.hpp"
#include "VideoManager.hpp"
#include "EventManager.hpp"
#include "Globals.hpp"
#include "Logger.hpp"

Thing::Game::Game(int argc, char* argv[]) :
    _is_running(false), _focus(false)
{
}

Thing::Game::~Game()
{
    DBG("Cleaning everything");

    _is_running = false;
    delete _video_manager;
    delete _event_manager;
    delete Globals::logger;
}

void Thing::Game::initialize(const Video::VideoMode& vmode)
{
    DBG("LET THERE BE LIGHT !!!");
    
    try
    {
        Globals::game = this;
        
        _video_manager = new Video::VideoManager();
        _video_manager->initialize(vmode);
        Globals::video = _video_manager;

        _event_manager = new Events::EventManager();
        _event_manager->initialize();
        Globals::event = _event_manager;

        _is_running = true; 
        _focus = true;
    } 
    catch(Thing::Utils::Exception &e)
    {
        ERROR(e.what());
    }
}

void Thing::Game::setName(const std::string& app_name)
{
    DBG(STG(FMT("Setting app name as '%s'") % app_name));
    _app_name = app_name;
    SDL_WM_SetCaption(app_name.c_str(), NULL);
}

void Thing::Game::update()
{
    _video_manager->update();
    _event_manager->update();
}

int Thing::Game::exec()
{
    DBG("Execute the game");

    if(_app_name.empty())
    { 
        DBG("No app name setted, setting default");
        setName("Game");
    }

    while(_is_running)
    {
        update();
    }


    DBG("Executed");
    return 0;
}
